import { Navigate, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { selectAuth, fetchUserInfo } from '@/store';
import { useEffect } from 'react';

export default function AuthGuard({ children }) {
  const location = useLocation();
  const dispatch = useDispatch();
  const { isAuthenticated, user } = useSelector(selectAuth);
  
  useEffect(() => {
    // 如果已认证但没有用户信息，则获取用户信息
    if (isAuthenticated && !user) {
      dispatch(fetchUserInfo());
    }
  }, [isAuthenticated, user, dispatch]);
  
  if (!isAuthenticated) {
    // 未登录时重定向到登录页面，并记录当前路径
    return <Navigate to="/login" state={{ from: location.pathname }} replace />;
  }
   return children;
 }